/**
 * @模块名：demo
 * @包名：com.example.http
 * @描述：HttpsUtil.java
 * @版本：1.0
 * @创建人：李凯
 * @创建时间：2021年2月23日下午4:26:26
 */
package com.example.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import org.apache.commons.ssl.KeyMaterial;
import org.apache.commons.ssl.SSLClient;
import org.apache.commons.ssl.TrustMaterial;

import com.example.xml.XmlUtil;

/**
 * @模块名：demo
 * @包名：com.example.http
 * @类名称：HttpsUtil
 * @类描述：
 * @版本：1.0
 * @创建人：李凯
 * @创建时间：2021年2月23日下午4:26:26
 */
public class HttpsUtil {

	public static void main(String[] args) throws Exception {
		SSLClient client = new SSLClient();
		client.addTrustMaterial(TrustMaterial.DEFAULT);
		client.addTrustMaterial(
				new KeyMaterial("E:\\workspace\\ebank-gateway\\src\\main\\resources\\static\\client.p12", "".toCharArray()));
		client.setCheckHostname(true);
		client.setCheckExpiry(false);
		client.setWantClientAuth(true);
		client.setKeyMaterial(
				new KeyMaterial("E:\\workspace\\ebank-gateway\\src\\main\\resources\\static\\client.p12", "".toCharArray()));
		String reqUrl = "https://60.13.219.130:16100/api/ibps/query/contract";
		URL url = new URL(reqUrl);
		HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
		https.setSSLSocketFactory(client);
		/* 发送数据 */
		https.setDoOutput(true);
		https.setDoInput(true);
		https.setHostnameVerifier(new HttpsUtil().new TrustAnyHostnameVerifier());
		https.setRequestMethod("POST");
		https.setRequestProperty("Accept", "*/*");
		https.setRequestProperty("Content-Type", "application/json");
		https.setRequestProperty("Appid", "M0dPzi02G2EO5LH3fJmlLuhWgVQ0");
		https.connect();
		OutputStreamWriter out = new OutputStreamWriter(https.getOutputStream(), "UTF-8"); //
		String path = XmlUtil.class.getResource("").getPath() + "/json.txt";
		String data = XmlUtil.readTxtFile(path, "UTF-8");
		out.append(data);
		out.flush();
		out.close();
		/* 接收数据 */
		BufferedReader in = new BufferedReader(new InputStreamReader(https.getInputStream()));
		String line;
		String result = "";
		while ((line = in.readLine()) != null) {
			result += line;
		}
		int code = https.getResponseCode();
		System.out.println("https请求状态：" + code);
		System.out.println("返回结果：" + result);
	}

	public class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

}
